package com.proactive.webapp.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.proactive.webapp.dao.CourseDAO;
import com.proactive.webapp.dao.DesignCategoryDAO;
import com.proactive.webapp.dao.DesignDAO;
import com.proactive.webapp.dao.DesignTagDAO;
import com.proactive.webapp.dao.MemberDAO;
import com.proactive.webapp.dao.MenuDAO;
import com.proactive.webapp.entity.Course;
import com.proactive.webapp.entity.Design;
import com.proactive.webapp.entity.DesignCategory;
import com.proactive.webapp.entity.DesignTag;
import com.proactive.webapp.entity.Member;
import com.proactive.webapp.entity.Menu;
import com.proactive.webapp.util.AwsUtil;
import com.proactive.webapp.util.CompressImage;
import com.proactive.webapp.util.DateConversion;
import com.proactive.webapp.util.FileUtil;
import com.proactive.webapp.util.MenuUtil;
import com.proactive.webapp.util.PageCount;

@Controller
public class MemberDesignController {
	ApplicationContext context =  new ClassPathXmlApplicationContext("spring-module.xml");
	
	@RequestMapping(value = "/addDesignCont", method = RequestMethod.GET)
	public ModelAndView addDesignCont(HttpSession session) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			model.setViewName("addDesign");
			List<DesignCategory> category1List = new ArrayList<DesignCategory>();
			List<DesignTag> tagList = new ArrayList<DesignTag>();
			DesignCategoryDAO designCategoryDAO = (DesignCategoryDAO) context.getBean("designCategoryDAO");
			DesignTagDAO designTagDAO = (DesignTagDAO) context.getBean("designTagDAO");
			category1List = designCategoryDAO.getList();
			tagList = designTagDAO.getTop(10, category1List.get(0).getId());
			List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
			model.addObject("menuList", menuList);
			model.addObject("category1", category1List);
			model.addObject("tag", tagList);
		}
		else
			model.setViewName("redirect:/login");
		return model;
	}
	
	@RequestMapping(value = "/addDesign", method = RequestMethod.POST)
	public ModelAndView addDesign(@ModelAttribute Design design, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			String path1 = session.getServletContext().getRealPath("resources/image/design");
			String path2 = session.getServletContext().getRealPath("resources/file/design");
			DateConversion dateConversion = new DateConversion();
			Date now = new Date();
			design.setAccount(loginMember.getAccount());
			
			//new AWS
			AwsUtil awsUtil = new AwsUtil();
	        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
	        awsUtil.getInstance();

			//upload image
			if(design.getImage().getSize() > 0){
				FileUtil fileUtil = new FileUtil(design.getImage().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
				
				//rename and move
				File targetFile = new File(path1, newFileName);
		        if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	design.getImage().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
				
				//compress image
				if(!fileUtil.getFileType().equals("gif")){
		    		CompressImage compressImage = new CompressImage();
		        	compressImage.compress(path1+"/", newFileName, 0, 0, false);
		        }
				
				//upload file AWS
				try {		        	
					awsUtil.uploadFile("resources/image/design/", targetFile);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				//delete local file
		        targetFile.delete();				
				design.setImagePath("resources/image/design/"+newFileName);
			}

			//upload file
			if(design.getFile().getSize() > 0){
				FileUtil fileUtil = new FileUtil(design.getFile().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
				
				//rename and move
				File targetFile = new File(path2, newFileName);
				design.setFileName(fileUtil.getLowerCaseName());
		        if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	design.getFile().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        
		        //upload file AWS
				try {
					awsUtil.uploadFile("resources/file/design/", targetFile);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        //delete local file
		        targetFile.delete();		        
				design.setFilePath("resources/file/design/"+newFileName);
			}
			else{
				design.setFilePath("");
				design.setFileName("");
			}
			DesignDAO designDAO = (DesignDAO)context.getBean("designDAO");
			int designID = designDAO.insert(design);
			DesignTagDAO designTagDAO = (DesignTagDAO) context.getBean("designTagDAO");	
			String[] tags = design.getTags().split(",");
			for(String tagName : tags){
				if(!tagName.equals("")){
					DesignTag designTag = new DesignTag();
					designTag.setDid(designID);
					designTag.setTag(tagName);
					designTagDAO.insert(designTag);
				}
			}
			model.setViewName("redirect:/showDesign?id="+designID);
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
	@RequestMapping(value = "/addPracticeCont", method = RequestMethod.GET)
	public ModelAndView addPracticeCont(HttpSession session, int cid) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			CourseDAO courseDAO = (CourseDAO)context.getBean("courseDAO");
			Course course = new Course();
			course.setId(cid);
			course = courseDAO.get(course);
			if(course.getStatus() == 1){
				model.setViewName("addPractice");
				List<DesignCategory> category1List = new ArrayList<DesignCategory>();
				List<DesignTag> tagList = new ArrayList<DesignTag>();
				DesignCategoryDAO designCategoryDAO = (DesignCategoryDAO) context.getBean("designCategoryDAO");
				DesignTagDAO designTagDAO = (DesignTagDAO) context.getBean("designTagDAO");
				category1List = designCategoryDAO.getList();
				tagList = designTagDAO.getTop(10, category1List.get(0).getId());
				List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
				model.addObject("menuList", menuList);
				model.addObject("category1", category1List);
				model.addObject("tag", tagList);
				model.addObject("course", course);
			}
			else 
				model.setViewName("redirect:/design");

		}
		else
			model.setViewName("redirect:/login");
		return model;
	}
	
	@RequestMapping(value = "/addPractice", method = RequestMethod.POST)
	public ModelAndView addPractice(@ModelAttribute Design design, HttpSession session, String memberNO, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			MemberDAO memberDAO = (MemberDAO) context.getBean("memberDAO");			
			Member member = new Member();
			member.setMemberNO(memberNO);
			member = memberDAO.getByMemberNO(member);
			loginMember = memberDAO.get(loginMember);
			String path1 = session.getServletContext().getRealPath("resources/image/design");
			String path2 = session.getServletContext().getRealPath("resources/file/design");
			DateConversion dateConversion = new DateConversion();
			Date now = new Date();
			design.setAccount(loginMember.getAccount());
			design.setWriterAccount(member.getAccount());
			
			//new AWS
			AwsUtil awsUtil = new AwsUtil();
	        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
	        awsUtil.getInstance();

			//upload images
			if(design.getImage().getSize() > 0){
				FileUtil fileUtil = new FileUtil(design.getImage().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
				
				//rename and move
				File targetFile = new File(path1, newFileName);
		        if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	design.getImage().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        
		        //compress image
				if(!fileUtil.getFileType().equals("gif")){
		    		CompressImage compressImage = new CompressImage();
		        	compressImage.compress(path1+"/", newFileName, 0, 0, false);
		        }
				
				//upload file AWS
				try {		        	
					awsUtil.uploadFile("resources/image/design/", targetFile);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
		        //delete local file
		        targetFile.delete();	
				design.setImagePath("resources/image/design/"+newFileName);
			}

			//upload file
			if(design.getFile().getSize() > 0){
				FileUtil fileUtil = new FileUtil(design.getFile().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
				
				//rename and move
				File targetFile = new File(path2, newFileName);
				design.setFileName(fileUtil.getLowerCaseName());
		        if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	design.getFile().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        
		        //upload file AWS
				try {
					awsUtil.uploadFile("resources/file/design/", targetFile);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        //delete local file
		        targetFile.delete();		        
				design.setFilePath("resources/file/design/"+newFileName);
			}
			else{
				design.setFilePath("");
				design.setFileName("");
			}
			DesignDAO designDAO = (DesignDAO)context.getBean("designDAO");
			int designID = designDAO.insertPractice(design);
			DesignTagDAO designTagDAO = (DesignTagDAO) context.getBean("designTagDAO");	
			String[] tags = design.getTags().split(",");
			for(String tagName : tags){
				if(!tagName.equals("")){
					DesignTag designTag = new DesignTag();
					designTag.setDid(designID);
					designTag.setTag(tagName);
					designTagDAO.insert(designTag);
				}
			}
			model.setViewName("redirect:/showDesign?id="+designID);
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
	@RequestMapping(value = "/memberDesign", method = RequestMethod.GET)
	public ModelAndView getMemberDesignList(HttpServletRequest request, HttpSession session) {
		ModelAndView model = new ModelAndView();
		Member loginMember = (Member)session.getAttribute("loginMember");
		if (request.getParameter("id") != null) {
			MemberDAO memberDAO = (MemberDAO) context.getBean("memberDAO");
			DesignDAO designDAO = (DesignDAO) context.getBean("designDAO");
			Member member = new Member();			
			List<Design> designList = new ArrayList<Design>();
			
			String memberNO = request.getParameter("id");
			int pageNow = request.getParameter("p")==null?1:Integer.parseInt(request.getParameter("p"));
			
			member.setMemberNO(memberNO);
			member = memberDAO.getByMemberNO(member);//用memberNO取得memberAccount
			if(member.getAccount()!=null){
				
				if(loginMember != null)
					member = memberDAO.getByLogin(member, loginMember.getAccount());//取得member資料
				int count = 0;
				if(member.isMyselfFlag())
					count = designDAO.countTotalByWriter(member.getAccount());
				else
					count = designDAO.countTotalByMember(member.getAccount());
				
				//set pager
				int pageSize = 9;
				String pageUrl = "memberDesign";
				String pageEndUrl1 = "&id="+memberNO;
				PageCount pageCount = new PageCount(pageNow, pageSize, count, pageUrl, pageEndUrl1);
				pageCount.calculate();
				
				if(member.isMyselfFlag())
					designList = designDAO.getListByWriter(member.getAccount(), pageCount.getStart(), pageSize);
				else
					designList = designDAO.getListByMember(member.getAccount(), pageCount.getStart(), pageSize);
				
				List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
				
				//set model
				model.addObject("page", pageCount);
				model.addObject("member", member);
				model.addObject("designList", designList);
				model.addObject("menuList", menuList);
				model.setViewName(loginMember!=null?"memberDesign1":"memberDesign2");
			}
			else
				model.setViewName("redirect:/");
			
		} 
		else
			model.setViewName(loginMember!=null?"redirect:/memberDesign?id="+loginMember.getMemberNO():"redirect:/login");

		
		return model;
	}
	
	@RequestMapping(value = "/actDesign", method = RequestMethod.POST)
	public ModelAndView actDesign(int id, String act, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){//檢查登入
			DesignDAO designDAO = (DesignDAO) context.getBean("designDAO");
			Design design = new Design();
			design.setId(id);
			design = designDAO.getByWriter(design);
			if(design.getAccount().equals(loginMember.getAccount())){//檢查是否為作者
				if(act.equals("delete")){//delete design
					//new AWS
					AwsUtil awsUtil = new AwsUtil();
			        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
			        awsUtil.getInstance();	
			        //delete image
					if(!design.getImagePath().equals("")){
						awsUtil.deleteFile(design.getImagePath());
					}
					//delete file
					if(!design.getFilePath().equals("")){
						awsUtil.deleteFile(design.getFilePath());
					}
					design.setStatus(3);
					
				}
				else if(act.equals("show")){//show design
					design.setStatus(1);
				}
				else if(act.equals("hide")){//hide design
					design.setStatus(2);
				}
				designDAO.updateStatus(design);
				model.setViewName("redirect:"+request.getHeader("referer"));
			}
			else 
				model.setViewName("redirect:/memberDesign");
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
	@RequestMapping(value = "/modiDesignCont", method = RequestMethod.GET)
	public ModelAndView modiDesignCont(HttpSession session, int id) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			DesignDAO designDAO = (DesignDAO) context.getBean("designDAO");
			Design design = new Design();
			design.setId(id);
			design = designDAO.getByWriter(design);
			if(design.getAccount().equals(loginMember.getAccount())){
				model.setViewName("modiDesign");
				List<DesignCategory> category1List = new ArrayList<DesignCategory>();
				List<DesignTag> tagList = new ArrayList<DesignTag>();
				List<DesignTag> tags = new ArrayList<DesignTag>();
				String tagString = "";
				DesignCategoryDAO designCategoryDAO = (DesignCategoryDAO) context.getBean("designCategoryDAO");
				DesignTagDAO designTagDAO = (DesignTagDAO) context.getBean("designTagDAO");
				category1List = designCategoryDAO.getList();
				tagList = designTagDAO.getTop(10, design.getCategoryID());
				tags = designTagDAO.getListByDesignID(id);
				for (int i=0; i<tags.size(); i++) {
					DesignTag tag = tags.get(i);
					tagString += tag.getTag();
					if(i < tags.size())
						tagString += ",";
				}
				for(int j=0; j<category1List.size(); j++){
					if(category1List.get(j).getId() == design.getCategoryID())
						category1List.get(j).setClassString("selected");
				}
				
				design.setTags(tagString);

				List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
				model.addObject("menuList", menuList);
				model.addObject("category1", category1List);
				model.addObject("tag", tagList);
				model.addObject("design", design);
			}
			else
				model.setViewName("redirect:/design");
			
		}
		else
			model.setViewName("redirect:/login");
		return model;
	}
	
	@RequestMapping(value = "/modiDesign", method = RequestMethod.POST)
	public ModelAndView modiDesign(@ModelAttribute Design design, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			DesignDAO designDAO = (DesignDAO)context.getBean("designDAO");
			Design oldDesign = new Design();
			oldDesign.setId(design.getId());
			oldDesign = designDAO.getByWriter(oldDesign);
			if(oldDesign.getAccount().equals(loginMember.getAccount())){
				//new AWS
				AwsUtil awsUtil = new AwsUtil();
		        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
		        awsUtil.getInstance();
		        
				String path = session.getServletContext().getRealPath("/");
				String path1 = session.getServletContext().getRealPath("resources/image/design");
				String path2 = session.getServletContext().getRealPath("resources/file/design");
				DateConversion dateConversion = new DateConversion();
				Date now = new Date();
				design.setAccount(loginMember.getAccount());
				
				//upload image
				if(design.getImage().getSize() > 0){
					FileUtil fileUtil = new FileUtil(design.getImage().getOriginalFilename());
					String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
					
					//rename and move
					File targetFile = new File(path1, newFileName);
			        if(!targetFile.exists()){
			            targetFile.mkdirs();
			        }
			        try {
			        	design.getImage().transferTo(targetFile);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }

			        //delete original file
			        if(!oldDesign.getImagePath().equals("")){
			        	awsUtil.deleteFile(oldDesign.getImagePath());
			        }
			        
		        	//compress image
					if(!fileUtil.getFileType().equals("gif")){
			    		CompressImage compressImage = new CompressImage();
			        	compressImage.compress(path1+"/", newFileName, 0, 0, false);
			        }
					
					//upload file AWS
			        try {
						awsUtil.uploadFile("resources/image/design/", targetFile);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			        
			        //delete local file
			        targetFile.delete();
		        	design.setImagePath("resources/image/design/"+newFileName);
					
					
				}
				else
		        	design.setImagePath(oldDesign.getImagePath());
				
				//upload file
				if(design.getFile().getSize() > 0){
					FileUtil fileUtil = new FileUtil(design.getFile().getOriginalFilename());
					String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
					
					//rename and move
					File targetFile = new File(path2, newFileName);
			        if(!targetFile.exists()){
			            targetFile.mkdirs();
			        }
			        try {
			        	design.getFile().transferTo(targetFile);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
			        
			        //delete original file
			        if(!oldDesign.getFilePath().equals("")){
			        	awsUtil.deleteFile(oldDesign.getFilePath());
			        }
			        
			        //upload file AWS
			        try {
						awsUtil.uploadFile("resources/file/design/", targetFile);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			        
			        //delete local file
			        targetFile.delete();
			        
		        	design.setFilePath("resources/file/design/"+newFileName);
		        	design.setFileName(fileUtil.getLowerCaseName());
				}
				else{
		        	design.setFilePath(oldDesign.getFilePath());
		        	design.setFileName(oldDesign.getFileName());
		        }
				
				if(!design.getFileUrl().equals("")){

		        	design.setFilePath("");
		        	design.setFileName("");
					if(!oldDesign.getFilePath().equals("")){
						awsUtil.deleteFile(oldDesign.getFilePath());
			        }
				}
				else
					design.setIsFile(1);
				
				if(oldDesign.getIsPractice() == 1){
					design.setWriter("");
					design.setWriterUrl("");
					design.setIsWriter(0);
				}
				designDAO.update(design);		
								
				DesignTagDAO designTagDAO = (DesignTagDAO) context.getBean("designTagDAO");	
				designTagDAO.delete(design.getId());
				String[] tags = design.getTags().split(",");
				for(String tagName : tags){
					if(!tagName.equals("")){
						DesignTag designTag = new DesignTag();
						designTag.setDid(design.getId());
						designTag.setTag(tagName);
						designTagDAO.insert(designTag);
					}
				}
				
			}
			model.setViewName("redirect:/memberDesign?id="+loginMember.getMemberNO());
			
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
}
